package com.shujia.window

import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.{EventTimeSessionWindows, ProcessingTimeSessionWindows}
import org.apache.flink.streaming.api.windowing.time.Time

object Demo02SessionWindow {
  /**
   * 会话窗口：超过一定时间间隔没有数据则会触发一次任务
   */
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    env.setParallelism(1)

    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    val assignTimeLineDS: DataStream[String] = linesDS.assignAscendingTimestamps(line => line.split(",")(1).toLong)

    assignTimeLineDS
      .map(line => (line.split(",")(0), 1))
      .keyBy(_._1)
      // 基于处理时间的会话窗口
      //      .window(ProcessingTimeSessionWindows.withGap(Time.seconds(5)))
      // 基于事件时间的会话窗口
      .window(EventTimeSessionWindows.withGap(Time.seconds(5)))
      .sum(1)
      .print()


    env.execute()


  }

}
